package com.dieusoft.box.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dieusoft.box.ship.entity.ShipExport;
import com.dieusoft.box.ship.service.ShipExportService;
import com.dieusoft.box.utils.DownPdf;
import com.dieusoft.box.utils.ExportWord;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/ship.export/")
@Slf4j
public class ExportController {
    @Autowired
    private ShipExportService shipExportService;
    @Autowired
    private CommonAPI commonAPI;

    private String demoFilePath = "/Users/dongwu/Desktop/temp/";
    private String tempFilePath = "/Users/dongwu/Desktop/test";

//    private String demoFilePath = "/usr/local/jzx-download-tempfile/";
//    private String tempFilePath = "/usr/local/jzx-download-tempfile/temp";

/******************************************************************导出-订舱委托书************************************************/
    /**
     * word导出-订舱委托书
     *
     * @return
     */
    @AutoLog(value = "word导出-订舱委托书")
    @ApiOperation(value = "word导出-订舱委托书", notes = "word导出-订舱委托书")
    @RequestMapping(value = "/wts/word")
    public void exportWordByDcwts(String id, int type, HttpServletRequest request, HttpServletResponse response) {
        log.info("word导出");
        log.info(id);
        ShipExport shipExport = shipExportService.getById(id);

        boolean flag = true;
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = mapper.writeValueAsString(shipExport);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = null;
        try {
            item = JSONObject.parseObject(json);
            for (Field field : oConvertUtils.getAllFields(shipExport)) {
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));
                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }

        Map<String, Object> params = JSON.parseObject(item.toString(), Map.class);
        String filePath = demoFilePath + "djh-dcwts.docx";
        if (type == 1) {
            filePath = demoFilePath + "hnwe-dcwts.docx";
        }
        try {
            ExportWord.exportWord(filePath, tempFilePath, id + ".docx", params, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 此处举例导入的为ProductVO中的数据
    // make方法 实现了应用PDF模板进行简单的导出 适合固定的模板
    @RequestMapping("/wts/pdf")
    public void fillTemplatePDF(String id, int type, HttpServletResponse response) throws IOException {
        // 生成的新文件路径及文件名
        String newPDFPath = "/Users/dongwu/Desktop/test/djh-dcwts-pdf.pdf";
        log.info("pdf导出");
        log.info(id);
        ShipExport shipExport = shipExportService.getById(id);
        String filePath = demoFilePath + "djh-dcwts-pdf.pdf";
        if (type == 1) {
            filePath = demoFilePath + "hnwe-dcwts-pdf.pdf";
        }
        DownPdf.fillTemplateByDcwts(shipExport, newPDFPath, filePath);

        //实现PDF在线预览
        File file = new File(newPDFPath);
        if (file.exists()) {
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }

        } else {
            log.info("文件不存在");
        }
        //删除下载到本机的文件
        file.delete();


    }

    /******************************************************************导出-入货通知书************************************************/
    /**
     * word导出-入货通知书
     *
     * @return
     */
    @AutoLog(value = "word导出-入货通知书")
    @ApiOperation(value = "word导出-入货通知书", notes = "word导出-入货通知书")
    @RequestMapping(value = "/rhtzs/word")
    public void exportWordByRhtzs(String id, int type, HttpServletRequest request, HttpServletResponse response) {
        log.info("word导出");
        log.info(id);
        ShipExport shipExport = shipExportService.getById(id);

        boolean flag = true;
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = mapper.writeValueAsString(shipExport);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = null;
        try {
            item = JSONObject.parseObject(json);
            for (Field field : oConvertUtils.getAllFields(shipExport)) {
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));
                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
        } catch (Exception e) {
            flag = false;
        }

        Map<String, Object> params = JSON.parseObject(item.toString(), Map.class);
        JSONObject jsonObject = JSONObject.parseObject(item.toString());
        JSONObject boxInfo = JSONObject.parseObject(jsonObject.getString("boxInfo"));
        //件重尺
        String pieceNumber = boxInfo.getString("pieceNumber");
        String totalWeight = boxInfo.getString("totalWeight");
        String totalVolume = boxInfo.getString("totalVolume");
        String pieceNumberUnit = boxInfo.getString("pieceNumberUnit");
        StringBuilder sbJcz = new StringBuilder();
        sbJcz.append(pieceNumber).append(pieceNumberUnit).append("/")
                .append(totalWeight).append(" KGS/")
                .append(totalVolume).append(" CBM");

        JSONArray boxList = JSONObject.parseArray(boxInfo.getString("boxList"));
        StringBuilder sbBox = new StringBuilder();
        for (int i = 0; i < boxList.size(); i++) {
            JSONObject boxItem = JSONObject.parseObject(boxList.get(i).toString());
            sbBox.append(boxItem.getString("boxtype")).append("*").append(boxItem.getString("boxl")).append(",");
        }
        params.put("today", DateUtils.formatDate());
        params.put("mainOffNumber", jsonObject.getString("mainOffNumber").replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", ""));
        params.put("jcz", sbJcz.toString());
        params.put("box", sbBox.toString());
        params.put("shipName", jsonObject.getString("shipName") + "/" + jsonObject.getString("voyageNumber"));
        params.put("entrustCompany", jsonObject.getString("entrustCompany_dictText"));

        String filePath = demoFilePath + "djh-rhtzs.docx";
        if (type == 1) {
            filePath = demoFilePath + "hnwe-rhtzs.docx";
        }
        try {
            ExportWord.exportWord(filePath, tempFilePath, id + ".docx", params, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 此处举例导入的为ProductVO中的数据
    // make方法 实现了应用PDF模板进行简单的导出 适合固定的模板
    @RequestMapping("/rhtzs/pdf")
    public void fillTemplatePDFByRhtzs(String id, int type, HttpServletResponse response) throws IOException {
        // 生成的新文件路径及文件名
        String newPDFPath = "/Users/dongwu/Desktop/test/djh-rhtzs-pdf.pdf";
        log.info("pdf导出");
        log.info(id);
        ShipExport shipExport = shipExportService.getById(id);
        String filePath = demoFilePath + "djh-rhtzs-pdf.pdf";
        if (type == 1) {
            filePath = demoFilePath + "hnwe-rhtzs-pdf.pdf";
        }
        boolean flag = true;
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = mapper.writeValueAsString(shipExport);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = null;
        try {
            item = JSONObject.parseObject(json);
            for (Field field : oConvertUtils.getAllFields(shipExport)) {
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));
                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
        } catch (Exception e) {
            flag = false;
        }

        DownPdf.fillTemplateByRhtzs(item, newPDFPath, filePath);

        //实现PDF在线预览
        File file = new File(newPDFPath);
        if (file.exists()) {
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }

        } else {
            log.info("文件不存在");
        }
        //删除下载到本机的文件
        file.delete();


    }
    /******************************************************************导出-电放保函************************************************/
    /**
     * word导出-电放保函
     *
     * @return
     */
    @AutoLog(value = "word导出-电放保函")
    @ApiOperation(value = "word导出-电放保函", notes = "word导出-电放保函")
    @RequestMapping(value = "/dfbh/word")
    public void exportWordByDfbh(String id, int type, HttpServletRequest request, HttpServletResponse response) {
        log.info("word导出");
        log.info(id);
        ShipExport shipExport = shipExportService.getById(id);

        boolean flag = true;
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = mapper.writeValueAsString(shipExport);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = null;
        try {
            item = JSONObject.parseObject(json);
            for (Field field : oConvertUtils.getAllFields(shipExport)) {
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));
                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
        } catch (Exception e) {
            flag = false;
        }

        Map<String, Object> params = JSON.parseObject(item.toString(), Map.class);
        JSONObject jsonObject = JSONObject.parseObject(item.toString());
        JSONObject boxInfo = JSONObject.parseObject(jsonObject.getString("boxInfo"));
        //件重尺
        String pieceNumber = boxInfo.getString("pieceNumber");
        String totalWeight = boxInfo.getString("totalWeight");
        String totalVolume = boxInfo.getString("totalVolume");
        String pieceNumberUnit = boxInfo.getString("pieceNumberUnit");
        StringBuilder sbJcz = new StringBuilder();
        sbJcz.append(pieceNumber).append(pieceNumberUnit).append("/")
                .append(totalWeight).append(" KGS/")
                .append(totalVolume).append(" CBM");
        params.put("today", DateUtils.formatDate());
        params.put("jcz", sbJcz.toString());
        params.put("mainOffNumber", jsonObject.getString("mainOffNumber").replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", ""));
        params.put("otherOffNumber", jsonObject.getString("otherOffNumber").replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", ""));
        params.put("portDepartureANDplaceDelivery", jsonObject.getString("portDeparture") + "/" + jsonObject.getString("placeDelivery"));
        params.put("shipName", jsonObject.getString("shipName") + "/" + jsonObject.getString("voyageNumber"));
        String filePath = demoFilePath + "djh-dfbh.docx";
        if (type == 1) {
            filePath = demoFilePath + "hnwe-dfbh.docx";
        }
        try {
            ExportWord.exportWord(filePath, tempFilePath, id + ".docx", params, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 此处举例导入的为ProductVO中的数据
    // make方法 实现了应用PDF模板进行简单的导出 适合固定的模板
    @RequestMapping("/dfbh/pdf")
    public void fillTemplatePDFByDfbh(String id, int type, HttpServletResponse response) throws IOException {
        // 生成的新文件路径及文件名
        String newPDFPath = "/Users/dongwu/Desktop/test/djh-dfbh-pdf.pdf";
        log.info("pdf导出");
        log.info(id);
        ShipExport shipExport = shipExportService.getById(id);
        String filePath = demoFilePath + "djh-dfbh-pdf.pdf";
        if (type == 1) {
            filePath = demoFilePath + "hnwe-dfbh-pdf.pdf";
        }
        boolean flag = true;
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = mapper.writeValueAsString(shipExport);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = null;
        try {
            item = JSONObject.parseObject(json);
            for (Field field : oConvertUtils.getAllFields(shipExport)) {
                if (field.getAnnotation(Dict.class) != null) {
                    String code = field.getAnnotation(Dict.class).dicCode();
                    String text = field.getAnnotation(Dict.class).dicText();
                    String table = field.getAnnotation(Dict.class).dictTable();
                    String key = String.valueOf(item.get(field.getName()));
                    //翻译字典值对应的txt
                    String textValue = translateDictValue(code, text, table, key);
                    item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
                }
                //date类型默认转换string格式化日期
                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    item.put(field.getName(), aDate.format(new Date((Long) item.get(field.getName()))));
                }
            }
        } catch (Exception e) {
            flag = false;
        }

        DownPdf.fillTemplateByDfbh(item, newPDFPath, filePath);

        //实现PDF在线预览
        File file = new File(newPDFPath);
        if (file.exists()) {
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }

        } else {
            log.info("文件不存在");
        }
        //删除下载到本机的文件
        file.delete();


    }

    private String translateDictValue(String code, String text, String table, String key) {
        if (oConvertUtils.isEmpty(key)) {
            return null;
        }
        StringBuffer textValue = new StringBuffer();
        String[] keys = key.split(",");
        for (String k : keys) {
            String tmpValue = null;
            log.debug(" 字典 key : " + k);
            if (k.trim().length() == 0) {
                continue; //跳过循环
            }
            if (!StringUtils.isEmpty(table)) {
                log.debug("--DictAspect------dicTable=" + table + " ,dicText= " + text + " ,dicCode=" + code);
                tmpValue = commonAPI.translateDictFromTable(table, text, code, k.trim());
            } else {
                tmpValue = commonAPI.translateDict(code, k.trim());
            }
            if (tmpValue != null) {
                if (!"".equals(textValue.toString())) {
                    textValue.append(",");
                }
                textValue.append(tmpValue);
            }

        }
        return textValue.toString();
    }
}
